package org.androbuzz;

import java.util.ArrayList;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.NotificationManager;
import android.app.TabActivity;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.view.ViewGroup;

//import android.gesture.Gesture;
//import android.gesture.GestureLibraries;
//import android.gesture.GestureLibrary;
//import android.gesture.GestureOverlayView;
//import android.gesture.Prediction;
//import android.gesture.GestureOverlayView.OnGesturePerformedListener;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;


public class AndroBuzzActivity extends TabActivity /*implements OnGesturePerformedListener*/ {
	
	// Set MenuItem ID
	private String TAG = "AndroBuzz.Main";
	private static final int MENU_REFRESH = 0x0;
    private static final int MENU_SETTINGS = 0x1;
	private static final int MENU_ACCOUNTS = 0x2;
	private static final int MENU_FILTERS = 0x3;
	private static final int MENU_QUIT = 0x4;
	private static final int MENU_ABOUT = 0x5;
	
	Intent svc;
	
//	private GestureLibrary mLibrary;
	
	// Set Dialog ID
	static final int ABOUT = 0;
	static final int QUIT = 1;
	
	private AndroBuzzOauthClient Oauth;

	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       
        
        Resources res = getResources(); // Resource object to get Drawables
        TabHost tabHost = getTabHost();  // The activity TabHost
        TabHost.TabSpec spec;  // Resusable TabSpec for each tab
        Intent intent;  // Reusable Intent for each tab
        
        Oauth = new AndroBuzzOauthClient(this);
        AndroBuzzAccount account = new AndroBuzzAccount(this);
        account.initialize();
        
        LayoutInflater.from(this).inflate(R.layout.main, tabHost.getTabContentView(), true);
        intent = new Intent(AndroBuzzActivity.this, AndroBuzzNearbyActivity.class);
        tabHost.addTab(tabHost.newTabSpec("nearby")
                .setIndicator("Nearby", res.getDrawable(android.R.drawable.ic_dialog_map))
                .setContent(intent));
        intent = new Intent(AndroBuzzActivity.this, AndroBuzzFeedActivity.class);
        tabHost.addTab(tabHost.newTabSpec("feed")
                .setIndicator("Feed", res.getDrawable(R.drawable.ic_tab_feeds))
                .setContent(intent));
        intent = new Intent(this, AndroBuzzBuddiesManagerActivity.class);
        tabHost.addTab(tabHost.newTabSpec("Followers")
        		.setIndicator("Followers", res.getDrawable(android.R.drawable.ic_menu_myplaces))
        		.setContent(intent));
        
        svc = new Intent(AndroBuzzActivity.this, AndroBuzzService.class);
        startService(svc);
        
        /*example webview
         *         
        WebView webview = (WebView) findViewById(R.id.webView1);
	   	String summary = "<html><body>You scored <b>Here is the first buzz in web view.</body></html>";
	   	webview.loadData(summary, "text/html", "utf-8");   
        */
        
//        mLibrary = GestureLibraries.fromRawResource(this, R.raw.gests );
//        if (!mLibrary.load()) {
//        	finish();
//        }
//        
//        GestureOverlayView gestures = (GestureOverlayView) findViewById(R.id.gestures);
//        gestures.addOnGesturePerformedListener(this);
    }
    
    public void onResume() {
    	super.onResume();
    	if (Oauth != null) {
    		Log.d(TAG, "Retrieving token");
    		Oauth.retrieveToken();
    		// Hack test: Activity back up to fast
    		try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    	} else {
    		Log.d(TAG, "Oauth client not initialzed :(");
    	}
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy(); 
    }
    
    /* Menu items */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	Boolean SupRetVal = super.onCreateOptionsMenu(menu);
    	SubMenu accounts = menu.addSubMenu(0, MENU_REFRESH, 1, "Refresh")
    					.setIcon(android.R.drawable.ic_menu_rotate);
        SubMenu settings = menu.addSubMenu(0, MENU_SETTINGS, 3, "Settings")
        				.setIcon(android.R.drawable.ic_menu_preferences);
        SubMenu filters = menu.addSubMenu(0, MENU_FILTERS, 2, "Filter")
        				.setIcon(android.R.drawable.ic_menu_share);
	    SubMenu quit = menu.addSubMenu(0, MENU_QUIT, 5, "Quit")
						.setIcon(android.R.drawable.ic_menu_close_clear_cancel);
		SubMenu about = menu.addSubMenu(0, MENU_ABOUT, 4, "About")
						.setIcon(android.R.drawable.ic_menu_info_details);
        return SupRetVal;
    }

    // Dialog Handler
    protected Dialog onCreateDialog(int id) {
    	Dialog dialog = null;
    	
        switch(id) {
        case QUIT:
        	AlertDialog.Builder builder = new AlertDialog.Builder(this);
		   	builder.setMessage("Do you really want to quit?")
		   			.setCancelable(false)
		   			.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
		   						public void onClick(DialogInterface dialog, int id) {
		   											stopService(svc);
		   											AndroBuzzActivity.this.finish();
		   						}
		   			})
		   			.setNegativeButton("No", new DialogInterface.OnClickListener() {
		   						public void onClick(DialogInterface dialog, int id) {
		   											dialog.cancel();
		   						}
		   			});
	        AlertDialog alert = builder.create();
	        return alert;
        default:
            dialog = null;
        }
        return dialog;
    }

    /** Menu Actions */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	Boolean SupRetVal = super.onOptionsItemSelected(item);
    	Log.d("AndroBuzz.menu", "MenuItem -> GetID : " + item.getItemId());
        switch (item.getItemId()) {
        case MENU_REFRESH:
        	popup("Refreshing buzz list");
        	// Add refresh function here.
        	return SupRetVal;
        case MENU_FILTERS:
        	this.popup("Filters not implemented yet!");
        	return SupRetVal;
        case MENU_SETTINGS:
            Intent i = new Intent(AndroBuzzActivity.this, AndrobuzzSettingsActivity.class);
            startActivityForResult(i, 0);
            return SupRetVal;
		case MENU_QUIT:
			showDialog(QUIT);
            return SupRetVal;
		case MENU_ABOUT:
			LayoutInflater About = LayoutInflater.from(this);
        	View view = About.inflate(R.layout.about, null);
        				new AlertDialog.Builder(AndroBuzzActivity.this)
        				.setTitle("About AndroBuzz")
        				.setIcon(R.drawable.icon)
        				.setView(view)
        				.setNeutralButton("Close", new DialogInterface.OnClickListener() {
							
							public void onClick(DialogInterface dialog, int whichButton) {
								Log.d("AndroBuzz.dialog", "Close pressed");								
							}
						}).show();
			return SupRetVal;
        }
        return false;
    }


//	public void onGesturePerformed(GestureOverlayView overlay, Gesture gesture) {
//		ArrayList<Prediction> predictions = mLibrary.recognize(gesture);
//
//		// We want at least one prediction
//		if (predictions.size() > 0) {
//			Prediction prediction = predictions.get(0);
//			// We want at least some confidence in the result
//			if (prediction.score > 1.0) {
//				// Change the tab
//				//Toast.makeText(this, prediction.name, Toast.LENGTH_SHORT).show();
//				TabHost tabHost = getTabHost();
//				if (prediction.name.equals("Fire Spell")) {
//					Toast.makeText(this, prediction.name + ": ok !!", Toast.LENGTH_SHORT).show();
//					tabHost.setCurrentTab(1);
//				}
//				else if (prediction.name == "action_left") {
//					Toast.makeText(this, prediction.name + ": ok !!", Toast.LENGTH_SHORT).show();
//					tabHost.setCurrentTab(0);
//				}
//			}
//		}
//	}
    public void popup(String message) {
    	Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }
}
